package com.abigdreamer.im.server.log;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.abigdreamer.im.server.tools.ServerUtils;

/**
 * 
 * 
 */
public class LoggerFileManager {

	/**
	 * 写日志信息
	 * @param msg
	 */
	public static void write(String msg){
		String loggerName=getDate()+"(001).log";
		File file=getWriteFile(loggerName);
		try {
			if(!file.exists()) {
				file.createNewFile();
			}
			ServerUtils.fileAppend(file, msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取所以日志文件
	 * @return
	 */
	public static File[] getLoggerFile(){
		String filePackage = "src/com/csu/server/log/";
        File file = new File(filePackage);
        FileListFilter filter=new FileListFilter();
        File[] files=file.listFiles(filter);
		return files;
	}
	
	/**
	 * 根据日期获得当日所有的日志文件
	 * @param date
	 * @return
	 */
	public static File[]  getLoggerFile(final String date){
		String filePackage = "src/com/csu/server/log/";
        File file = new File(filePackage);
        FilenameFilter filter=new FilenameFilter(){
			public boolean accept(File dir, String name) {
				boolean fileEndOK = name.endsWith('.' + "log");
				boolean fileStartOK = name.startsWith(date);
				return fileEndOK&&fileStartOK;
			}
        };
        File[] files=file.listFiles(filter);
		return files;
	}
	/**
	 * 根据日志的名字获取日志文件
	 * @param loggerName
	 * @return
	 */
	public static File getWriteFile(String loggerName){
		File file=null;
		file=ServerUtils.getFile(LoggerFileManager.class.getPackage(), loggerName);
		if(file.length()>1*1024*1024){
			int filenum=Integer.parseInt(loggerName.substring(11,14))+1;
			String num=null;
			if(filenum<10){
				num="00"+filenum;
			}else if(filenum<100){
				num="0"+filenum;
			}else{
				num=""+filenum;
			}
			String newName=getDate()+"("+num+").log";
			file=ServerUtils.getFile(LoggerFileManager.class.getPackage(), newName);
			file=getWriteFile(file.getName());
		}
		return file;
	}
	/**
	 * 获取当日的日期
	 * @return
	 */
	private static String  getDate(){
		Date date=new Date();
		SimpleDateFormat myDateFmt=new SimpleDateFormat("yyyy-MM-dd");
		return myDateFmt.format(date);
	}
	
}

/**
 * 日志文件过滤器
 */
class FileListFilter implements FilenameFilter {
	private String extension="log";
	public boolean accept(File dir, String name) {
		boolean fileOK = true;
		if (extension != null) {
		   fileOK = name.endsWith('.' + extension);
		}
		return fileOK;
	}
}
